<template>
  <div v-loading="biggestLoading" class="app-container" style="display: flex;flex-direction: column;">
    <div style="display: flex;">
      <div style="flex: 1;display: flex;flex-direction: column;">
        <div style="display: flex;gap: 10px;">
          <el-form :model="leftParams" ref="leftFormRef" label-width="100px" @submit.prevent>
            <el-form-item label="质检 Port 口" prop="port" label-position="left">
              <el-select
                v-model="leftParams.port"
                placeholder="请选择 Port 口"
                :disabled="selectFlag"
                style="width: 250px;"
                @change="changePort"
              >
                <el-option
                  v-for="item in portList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div>
            <el-button type="warning" plain :disabled="!leftParams.port" @click="missionCancel">
              Port 口任务取消
            </el-button>
          </div>
        </div>
        <div>
          <el-form :model="leftParamsTwo" ref="leftTwoFormRef" label-width="100px" @submit.prevent>
            <!-- <el-form-item label="箱号" prop="boxCode" label-position="left">
              <el-input
                v-model="leftParamsTwo.boxCode"
                placeholder="请扫描箱号"
                clearable
                style="width: 250px"
                :disabled="scanFlag"
                @keyup.enter="lightUp"
                @blur="lightUp"
              />
            </el-form-item> -->
            <el-form-item label="Reel ID" prop="reelId" label-position="left">
              <el-input
                v-model="leftParamsTwo.reelId"
                placeholder="请扫描 Reel ID"
                clearable
                style="width: 250px"
                :disabled="scanFlag"
                @keyup.enter="extraInfo(leftParamsTwo.reelId)"
                @blur="extraInfo(leftParamsTwo.reelId)"
                />
            </el-form-item>
          </el-form>
          <!-- <el-button type="primary" style="width: 275px;" :loading="btn.bind" :disabled="scanFlag" plain @click="bind">物料绑定</el-button> -->
        </div>
      </div>
      <div style="flex: 1;display: flex;flex-direction: column;gap: 20px;">
        <div>
          <el-button plain type="success" :disabled="btn.transform" @click="openModal">搬运任务触发</el-button>
          <!-- <el-button plain type="success" @click="goToMaterialContainer">物料载具</el-button> -->
          <el-button plain type="danger" :disabled="!leftParams.port" @click="errorReport">Port口 异常上报</el-button>
        </div>
        <el-form :model="rightParams" ref="rightFormRef" label-width="120px">
          <el-form-item label="料箱编号" prop="boxCode" label-position="left">
            <el-input
              v-model.trim="rightParams.boxCode"
              placeholder="请扫描料箱编号"
              style="width: 250px"
              @keyup.enter="getProgress"
            />
            <el-button type="warning" plain style="margin-left: 10px;" :disabled="!rightParams.boxCode" @click="clearFlag">清除</el-button>
          </el-form-item>
          <!-- <el-form-item label="质检单号" prop="qualityOrder" label-position="left">
            <el-input
              v-model="rightParams.qualityOrder"
              clearable
              style="width: 250px"
              readonly
            />
          </el-form-item> -->
          <el-form-item label="扫码进度" prop="totalProgress" label-position="left">
            <el-input
              v-model="rightParams.totalProgress"
              clearable
              placeholder="扫描料箱编号后显示"
              style="width: 250px"
              readonly
            />
          </el-form-item>
          <el-form-item label="已扫码数量" prop="totalScannedCount" label-position="left">
            <el-input
              v-model="rightParams.totalScannedCount"
              clearable
              placeholder="扫描料箱编号后显示"
              style="width: 250px"
              readonly
            />
          </el-form-item>
          <el-form-item label="需扫码总数" prop="totalNeedScanCount" label-position="left">
            <el-input
              v-model="rightParams.totalNeedScanCount"
              clearable
              placeholder="扫描料箱编号后显示"
              style="width: 250px"
              readonly
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div style="flex: 1;display: flex;flex-direction: column;gap: 10px;">
      <div style="font: 600;font-size: large;">取料任务清单:</div>
      <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
      <el-table
        v-loading="btn.loading"
        :data="list"
        :span-method="objectSpanMethod"
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column prop="qualityCode" align="center" label="质检任务单号" />
        <el-table-column prop="materialCode" align="center" label="物料码" />
        <el-table-column prop="batchNo" align="center" label="批次号" />
        <el-table-column prop="isUrgent" align="center" label="紧急程度">
          <template #default="scope">
            <dict-tag :options="is_urgent" :value="scope.row.isUrgent"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Reel ID" align="center" label="Reel ID" width="250"/>
        <!-- <el-table-column prop="operatorId" align="center" label="操作人ID" /> -->
        <el-table-column prop="isScanned" align="center" label="扫描状态">
          <template #default="scope">
            <dict-tag :options="quality_scan_status" :value="scope.row.isScanned"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" align="center" label="任务状态">
          <template #default="scope">
            <dict-tag :options="quality_status" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="qualityResult" align="center" label="质检结果">
          <template #default="scope">
            <dict-tag :options="quality_result" :value="scope.row.qualityResult"></dict-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              width="280px"
              class="box-item"
              icon-color="red"
              placement="top"
              :title="`此操作将会将${scope.row.reelId}物料从${scope.row.boxCode}箱子中解绑, 是否继续?`"
              >
              <template #reference>
                <el-button type="warning" icon="Close" :loading="btn.unBind === scope.$index">解绑</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page-sizes="[10, 30, 50, 100]"
          v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
      </template>
      </TableScrollContainer>
    </div>
    <!-- modal -->
    <el-dialog
      v-model="dialogVisible"
      title="操作提示"
      width="500"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <span style="font-size: large;">点击确认将 Port 口任务取消, 是否继续?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmCancel">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- modal2 -->
    <el-dialog
      v-model="modalTwo"
      title="操作提示"
      width="500"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <span style="font-size: large;">点击确认将开始触发搬运任务, 是否继续?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="modalTwo = false">取消</el-button>
          <el-button type="primary" :loading="btn.transform" @click="confirmTransform">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <div class="ban-reason">
      <el-dialog
        title="Port口 异常上报"
        v-model="reasonVisible"
        width="400px"
        :close-on-click-modal="false"
        :before-close="reasonClose"
       >
        <div style="display: flex;flex-direction: column;gap: 10px;">
          <div style="display: flex;align-items: center;">
            <span style="width: 80px;">Port 口</span>
            <el-input v-model="errorPort" readonly></el-input>
          </div>
          <el-input v-model="reason" type="textarea" placeholder="请输入异常原因"></el-input>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="reasonClose">取 消</el-button>
            <el-button type="primary" :loading="btn.error" @click="confirmReport">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
 
<script setup name="QualityWork">
import { errorReportAPI } from "@/api/work/stockUp"
import { getListAPI, transformAPI, executeQualityAPI, getProgressAPI, controlLightAPI } from "@/api/work/qualityWork"
import { getPortInfoAPI  } from "@/api/work/stockUp"
import useListDataStore from '@/store/modules/listData'
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'
const { proxy } = getCurrentInstance()
const { is_urgent, quality_status, quality_scan_status, quality_result } = proxy.useDict('is_urgent', 'quality_status', 'quality_scan_status', 'quality_result')
const route = useRoute()
const reason = ref('')
const reasonVisible = ref(false)
const errorPort = ref('')
const list = ref([])
const scanInfo = ref({})
const scanFlag = ref(true)
const biggestLoading = ref(false)
const total = ref(0)
const btn = reactive({
  transform: false,
  bind: false,
  loading: false,
  unBind: '',
  error: false
})
const selectFlag = ref(false)
const dialogVisible = ref(false)
const modalTwo = ref(false)
const data = reactive({
  queryParams: {
    qualityCodes: null,
    pageNum: 1,
    pageSize: 10
  },
  form: {},
  leftParams: {
    port: ''
  },
  leftParamsTwo: {
    boxCode: '',
    reelId: ''
  },
  rightParams: {
    reelId: '',
    boxType: '',
    orderCode: '',
    inboundProgress: '',
    plantCode: '',
    materialCode: ''
  },
  rules: {
  }
})

const { queryParams, leftParams, leftParamsTwo, rightParams, form, rules } = toRefs(data)

const reasonClose = async() => {
  reasonVisible.value = false
}

const getErrorPort = () => {
  leftParams.value.port
  const errorIndex = portList.value.findIndex(item => {
    return item.value === leftParams.value.port
  })
  errorPort.value = portList.value[errorIndex].label
}

const errorReport = () => {
  // 异常上报
  getErrorPort()
  reasonVisible.value = true
}

const confirmReport = async() => {
  try {
    btn.error = true
    const res = await errorReportAPI({
      portId: leftParams.value.port,
      remark: reason.value
    })
    if (res.errCode === '1') {
      reasonVisible.value = false
      proxy.$modal.msgSuccess(res.msg)
      proxy.resetForm("leftFormRef")
      selectFlag.value = false
      clearFlag()
      getPortInfo()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } finally {
    btn.error = false
  }
}

const getProgress = async(val) => {
  // console.log(rightParams.value.boxCode)
  const res = await getProgressAPI({
    boxCode: rightParams.value.boxCode
  })
  // console.log(res)
  if (res.errCode === '1') {
    rightParams.value.totalProgress = res.data.data.totalProgress
    rightParams.value.totalScannedCount = res.data.data.totalScannedCount
    rightParams.value.totalNeedScanCount = res.data.data.totalNeedScanCount
    // scanFlag.value = false
    if (val === 'refresh') return
    proxy.$msgbox({
      title: '提升',
      message: '是否开始亮灯取料?',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(async() =>{
      try {
        biggestLoading.value = true
        const res = await controlLightAPI({
          boxCode: rightParams.value.boxCode
        })
        if (res.errCode === '1') {
          scanFlag.value = false
          proxy.$modal.msgSuccess(res.msg)
        } else {
          scanFlag.value = false
          proxy.$modal.msgWarning(res.msg)
        }
      } finally {
        biggestLoading.value = false
      }
    })
  }
}

const getList = async() => {
  try {
    btn.loading = true
    const res = await getListAPI(queryParams.value)
    list.value = res.data.page.records
    total.value = res.data.page.total
  } finally {
    btn.loading = false
  }
}
getList()

const extraInfo = async(val) => {
  if (!leftParamsTwo.value.reelId) return proxy.$modal.msgWarning('请扫描Reel Id')
  // console.log(val)
  if (val.includes(';')) {
    const array = val.split(';')
    scanInfo.value = {
      reelId: array[7].slice(1)
    }
    leftParamsTwo.value.reelId = scanInfo.value.reelId
    executeQuality('refresh')
  } else {
    executeQuality('refresh')
  }
}

const executeQuality = async(val) => {
  console.log('成功')
  const res = await executeQualityAPI({
    reelId: leftParamsTwo.value.reelId
  })
  if (res.errCode === '1') {
    proxy.$modal.msgSuccess(res.msg)
    scanInfo.value = {}
    proxy.resetForm("leftTwoFormRef")
    getList()
    if (val === 'refresh') {
      getProgress('refresh')
    }
  } else {
    proxy.$modal.msgWarning(res.msg)
  }
}

// const useAPILogi = async() => {
//   const res = await getBoxTypeAPI({
//     scanCode: rightParams.value.reelId
//   })
//   if (res.errCode === '1') {
//     if (!res.data.reelInfo.recommendBoxType) {
//       rightParams.value.reelId = ''
//       return proxy.$modal.msgWarning(`物料${res.data.reelInfo.materialCode}未配置标准箱类型，请在PC端维护其标准箱类型`)
//     }
//     rightParams.value.boxType = res.data.reelInfo.recommendBoxType || null
//     rightParams.value.plantCode = res.data.reelInfo.plantCode
//     rightParams.value.orderCode = res.data.reelInfo.inboundOrderCode
//     rightParams.value.materialCode = res.data.reelInfo.materialCode
//     rightParams.value.inboundProgress = res.data.reelInfo.inboundProgress
//     proxy.$modal.msgSuccess(res.msg)
//     scanFlag.value = false
//   } else {
//     proxy.resetForm("rightFormRef")
//     proxy.$modal.msgWarning(res.msg)
//   }
// }

const clearFlag = () => {
  proxy.resetForm("rightFormRef")
  proxy.resetForm("leftTwoFormRef")
  scanFlag.value = true
}

const lightUp = async() => {
  if (list.value.length === 0) {
    return proxy.$modal.msgWarning('暂无待质检物料')
  }
  const res = await lightUpAPI({
    boxCode: leftParamsTwo.value.boxCode,
    qualityCode: list.value[0].qualityCode
  })
  if (res.errCode === '1') {
    proxy.$modal.msgSuccess(res.msg)
  } else {
    leftParamsTwo.value.boxCode = ''
    proxy.$modal.msgWarning(res.msg)
  }
}

const openModal = () => {
  modalTwo.value = true
}

const confirmTransform = async() => {
  try {
    btn.transform = true
    const submitForm = {
      portId: leftParams.value.port
    }
    const res = await transformAPI(submitForm)
    if (res.errCode === '1') {
      modalTwo.value = false
      getList()
      proxy.$modal.msgSuccess(res.msg)
      scanFlag.value = false
    } else {
      proxy.$modal.msgWarning(res.msg)
    }
  } finally {
    btn.transform = false
  }
}

const bind = async() => {
//   try {
//     btn.bind = true
//     const res = await bindAPI({
//       boxCode: leftParamsTwo.value.boxCode,
//       scanCode: leftParamsTwo.value.reelId,
//       portId: leftParams.value.port
//     })
//     if (res.errCode === '1') {
//       leftParamsTwo.value.reelId = ''
//       // 右边更新
//       // TODO:物料用完的情况
//       rightParams.value.boxType = res.data.reelInfo.recommendBoxType || null
//       rightParams.value.plantCode = res.data.reelInfo.plantCode || null
//       rightParams.value.orderCode = res.data.reelInfo.inboundOrderCode || null
//       rightParams.value.materialCode = res.data.reelInfo.materialCode || null
//       rightParams.value.inboundProgress = res.data.reelInfo.inboundProgress || null
//       proxy.$modal.msgSuccess(res.msg)
//     } else {
//       proxy.$modal.msgWarning(res.msg)
//     }
//   } finally {
//     btn.bind = false
//   }
}

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
//   if (column.property === 'boxCode') {
//     if (rowIndex > 0 && row.boxCode === list.value[rowIndex - 1].boxCode) {
//       return {
//         rowspan: 0,
//         colspan: 1
//       }
//     }
//     let rowspan = 1
//     for (let i = rowIndex + 1; i < list.value.length; i++) {
//       if (list.value[i].boxCode === row.boxCode) {
//         rowspan++
//       } else {
//         break
//       }
//     }
//     return {
//       rowspan: rowspan,
//       colspan: 1
//     }
//   }
//   // 其他列不进行合并
  return {
    rowspan: 1,
    colspan: 1
  }
}

const changePort = () => {
  selectFlag.value = true
}

const missionCancel = () => {
  dialogVisible.value = true
}

const goToMaterialContainer = () => {
}

const unBind = async(row, index) => {
//   console.log(row)
//   const submitForm = {
//     containerId: row.boxCode,
//     reelId: row.reelId,
//     orderNumber: route.query.inboundOrderCode
//   }
//   try {
//     btn.unBind = index
//     const res = await unBindAPI(submitForm)
//     if (res.errCode === '1') {
//       getList()
//       proxy.$modal.msgSuccess(res.msg)
//     } else {
//       proxy.$modal.msgSuccess(res.msg)
//     }
//   } finally {
//     btn.unBind = ''
//   }
}

const portList = ref([])
const getPortInfo = async() => {
  const res = await getPortInfoAPI()
  portList.value = res.data.portList
    .filter(val => val.type === '1')
    .map(item => {
      return {
        value: item.portId,
        label: item.portName
      }
    })
}

getPortInfo()

const handleClose = () => {
  dialogVisible.value = false
  modalTwo.value = false
}

const confirmCancel = () => {
  dialogVisible.value = false
  selectFlag.value = false
  leftParams.value.port = ''
}
</script>

<style lang="scss" scoped>
.popconfirm-base-box .box-item {
  width: 200px;
  margin-top: 10px;
}

::v-deep .el-dialog {
  transform: none;
  left: 0;
  position: relative;
  margin: 300px auto !important;
}
</style>